package cis350.pcr.activities;

import java.util.ArrayList;
import cis350.pcr.AutoCompleteAdapter;
import cis350.pcr.CodeLookupDB;
import cis350.pcr.R;
import cis350.pcr.SearchDB;
import cis350.pcr.SearchHandler;
import cis350.pcr.types.*;
import cis350.pcr.types.Type.SearchType;

import com.loopj.android.http.AsyncHttpResponseHandler;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

/**
 * 
 * @author Perk Jeff Eric Tata
 * 
 */
public class SearchActivity extends Activity {
	/** Called when the activity is first created. */

	SearchHandler handler;
	AutoCompleteAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);

		handler = new SearchHandler(this);
		handler.stopLoadingDialog();//stop loadingDialog if it's there

		AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autosearch);

		adapter = new AutoCompleteAdapter(this, handler.codeDB.getSearchCursor("", 1, 1, 1));
		textView.setAdapter(adapter);
		textView.setHint("");
		textView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
				final String term = adapter.getTerm(position);
				final String path = adapter.getCode(position);
				final SearchType type = adapter.getType(position);
				Log.d("Autocomplete", path);
				handler.search(path, term, type, "none");
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//handler.showLoadingDialog();
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.action_search, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_help:
			Log.v("menu", "clicked");
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.search_help).setCancelable(true)
			.setNegativeButton("Close", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			// use builder.create() to create the dialog before showing it
			builder.show();
			return true;
		case R.id.menu_settings:
			Intent nextScreen = new Intent(getApplicationContext(), SettingsActivity.class);
			startActivity(nextScreen);
			return true;
		case R.id.menu_back:
			super.onBackPressed();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		handler.codeDB.close();
	}

	@Override
	public void onResume() {
		super.onResume();
		AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autosearch);
		textView.setText("");
		textView.requestFocus();
	}

	@Override
	public void onBackPressed() {
		if (handler.loadingDialog != null && handler.loadingDialog.isShowing()){
			handler.loadingDialog.dismiss();
			handler.loadingDialog = null;}
		else
			super.onBackPressed();
	}

	public void onRandomClick(View view) {
		String[] result = new String[2];
		SearchType type = handler.codeDB.getRandom(result);
		String path = result[0];
		String term = result[1];
		
		Log.d("Random", path);
		handler.search(path, term, type, "none");

//		new LoadRandomTask().execute(null, null, null);
	}

	public void onRecentClick(View view) {
		new LoadRecentTask().execute(this, null, this);
	}

	public void onBrowseDepts(View view) {
		new LoadDeptTask().execute(this, null, this);

	}

	public void onBrowseInstructors(View view) {
		new LoadInstructorTask().execute(this, null, this);
	}

	/**
	 * Class handling RandomSearch in background thread
	 */
	private class LoadRandomTask extends AsyncTask<Void, Void, Void>{
		String[] result;
		SearchType type;
		String path;
		String term;

		@Override
		protected void onPreExecute(){
			Toast.makeText(getApplicationContext(), R.string.loading, Toast.LENGTH_LONG).show();
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			result = new String[2];
			type = handler.codeDB.getRandom(result);
			path = result[0];
			term = result[1];
			return null;			
		}
		@Override
		protected void onPostExecute(Void params){
			Log.d("Random", path);
			handler.search(path, term, type, "none");
		}

		
	}
	
	/**
	 * Class handling RecentSearch in background thread
	 *
	 */
	private class LoadRecentTask extends AsyncTask<SearchActivity, Void, SearchActivity>{
		ArrayList<String> path;
		ArrayList<String> term;
		ArrayList<SearchType> type;       
		@Override
		protected void onPreExecute(){
			Toast.makeText(getApplicationContext(), R.string.loading, Toast.LENGTH_LONG).show();
		}

		@Override
		protected SearchActivity doInBackground(SearchActivity... params) {
			path = new ArrayList<String>();
			term = new ArrayList<String>();
			type = new ArrayList<SearchType>();
			handler.searchDB.getRecent(path, term, type);
			return params[0];
		}
		
		@Override
		protected void onPostExecute(SearchActivity activity ){
			CharSequence[] tempList = {"No Result"};
			if(term.size() > 0){
				tempList= term.toArray(new String[term.size()]);
			}
			final CharSequence[] list = tempList; 
			
			AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AlertDialogCustom));
			builder.setTitle("Recent Searches");

			builder.setCancelable(true).setItems(list, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int index) {
					handler.search(path.get(index), term.get(index), type.get(index), "none");
				}
			});
			
			AlertDialog alert = builder.create();
			alert.show();
		}
		
	}

	/**
	 * Class handling Instructor-Search using in background thread
	 *
	 */
	private class LoadInstructorTask extends AsyncTask<SearchActivity, Void, SearchActivity>{
		ArrayList<String> path;
		ArrayList<String> term;
		ArrayList<String> name;
       
		@Override
		protected void onPreExecute(){
			Toast.makeText(getApplicationContext(), R.string.loading, Toast.LENGTH_LONG).show();
		}

		@Override
		protected SearchActivity doInBackground(SearchActivity... params) {
			path = new ArrayList<String>();
			term = new ArrayList<String>();
			name = new ArrayList<String>();
			handler.codeDB.getAllProfs(path, term, name);
			return params[0];
		}
		
		@Override
		protected void onPostExecute(SearchActivity activity ){
			CharSequence[] tempList = {"No Results"};
			if(name.size() > 0){
				tempList = name.toArray(new String[name.size()]);
			}
			final CharSequence[] list = tempList;

			AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AlertDialogCustom));
			builder.setTitle("Instructors");
			builder.setCancelable(true).setItems(list, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int index) {

					handler.search("instructors/" + path.get(index) + "/reviews", term.get(index), Type.SearchType.INSTRUCTOR, "none");
				}
			});
			AlertDialog alert = builder.create();
			alert.show();

		}
		
	}

    /**
     * Class handling Department Search using background thread
     *
     */
	private class LoadDeptTask extends AsyncTask<SearchActivity, Void, SearchActivity>{
		ArrayList<String> path;
		ArrayList<String> term;
		ArrayList<String> name;
       
		@Override
		protected void onPreExecute(){
			Toast.makeText(getApplicationContext(), R.string.loading, Toast.LENGTH_LONG).show();
		}

		@Override
		protected SearchActivity doInBackground(SearchActivity... params) {
			path = new ArrayList<String>();
			term = new ArrayList<String>();
			name = new ArrayList<String>();
			handler.codeDB.getAllDepts(path, term, name);
			return params[0];
		}
		
		@Override
		protected void onPostExecute(SearchActivity activity){
			CharSequence[] tempList = {"No Results"};
			if(name.size() > 0){
				tempList = name.toArray(new String[name.size()]);
			}

			final CharSequence[] list = tempList;

			AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AlertDialogCustom));
			builder.setTitle("Departments");
			builder.setCancelable(true).setItems(list, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int index) {
					handler.search("depts/" + path.get(index), term.get(index), Type.SearchType.DEPT, "none");

				}
			});
			AlertDialog alert = builder.create();
			alert.show();

		}
		
	}

}